package com.atguigu.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.config.AlipayConfigTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayAsyncVo;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class OrderPayListener {


    @Autowired
    private AlipayConfigTemplate alipayConfigTemplate;

    @Autowired
    private OrderService orderService;

    @RequestMapping(value = "/payed/notify")
    public String payOrder(PayAsyncVo payAsyncVo, HttpServletRequest request){
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key:parameterMap.keySet()) {
            String[] value = parameterMap.get(key);
            String valueStr="";
            for (int i = 0; i <value.length ; i++) {
                valueStr =(i == value.length-1) ? valueStr + value[i]
                        : valueStr + value[i] + ",";
            }
            params.put(key,valueStr);
        }
        try {
            //验签
            boolean b = AlipaySignature.rsaCheckV1(params, alipayConfigTemplate.getAlipay_public_key(),
                    alipayConfigTemplate.getCharset(), alipayConfigTemplate.getSign_type());
            if(b){
                String result= orderService.handlePayResult(payAsyncVo);
                return result;
            }

        } catch (AlipayApiException e) {
            log.error("支付宝验签失败");
            throw new RuntimeException(e);
        }
        return "error";
    }
}
